package com.jjz.id.model;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.jjz.id.common.BaseEntity;
import com.jjz.id.common.Noun;
import com.jjz.id.common.validation.PasswordGroup;
import jakarta.validation.constraints.Pattern;
import lombok.Data;
import org.springframework.security.core.userdetails.UserDetails;


import java.io.Serializable;
import java.time.Instant;
import java.util.List;
import java.util.Set;

/**
 * @author ZJL
 * @create 2025-05-27-16:09
 */
@TableName("oauth2_user_info")
@Data
public class UserInfo extends BaseEntity implements UserDetails, Serializable {
    @TableField(
            exist = false
    )
    private static final long serialVersionUID = 1L;
    @TableId(
            type = IdType.ASSIGN_ID
    )
    private String id;
    private @Pattern(
            regexp = "^[a-z][a-zA-Z0-9]{5,30}$",
            message = "账号首字母必须是英文字母，可以有数字，长度必须在6-30位"
    ) String username;
    private @Pattern(
            regexp = "\"^(?![0-9]+$)(?![^0-9]+$)(?![a-zA-Z]+$)(?![^a-zA-Z]+$)(?![a-zA-Z0-9]+$)[a-zA-Z0-9\\\\S]{8,30}",
            message = "密码必须包含数字、字母和特殊字符，且长度8-30",
            groups = {PasswordGroup.class}
    ) String password;
    @JsonFormat(
            pattern = "yyyy-MM-dd HH:mm:ss",
            timezone = "GMT+8"
    )
    private Instant passwordExpiresAt;
    private Instant passwordUpdateTime;
    private Integer lockoutEnabled;
    private Instant lockoutEndDate;
    private String nickName;
    private String realName;
    private Integer realNameCertified;
    private String idCode;
    private Integer idType;
    private String phoneNumber;
    private String avatarUrl;
    private String email;
    private Integer gender;
    private Instant birthday;
    private String userType;
    @TableField("enabled")
    private Integer enabledFlag;
    @TableField(
            exist = false
    )
    private String genderString;
    @TableField(
            exist = false
    )
    private Set<Role> authorities;
    @TableField(
            exist = false
    )
    private List<String> roleIds;

    public boolean isAccountNonExpired() {
        return Noun.INT_1.equals(this.enabledFlag);
    }

    public boolean isAccountNonLocked() {
        return !Noun.INT_1.equals(this.lockoutEnabled) && (this.lockoutEndDate == null || !Instant.now().isBefore(this.lockoutEndDate));
    }

    public boolean isCredentialsNonExpired() {
        return this.passwordExpiresAt == null || !this.passwordExpiresAt.isBefore(Instant.now());
    }

    public boolean isEnabled() {
        return Noun.INT_1.equals(this.enabledFlag);
    }
}
